/*
 * Created on Apr 6, 2007
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Duong Nguyen Quang
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class ZipResponse {
	public static void write(HttpServletRequest request,
			HttpServletResponse response, String inputString, String encodeType) {
		try {
			// System.out.println("enter ZIP response");
			// -----------------zip-----------------
			// -----------endcoding header--------------
			if (encodeType == "" || encodeType == null) {
				encodeType = "utf-8";
			}
			boolean supportsGzip = false;
			String enc = request.getHeader("Accept-Encoding");

			if (enc != null) {
				{
					enc.replaceAll("\\s+", "").toLowerCase();
					supportsGzip = enc.indexOf("gzip") != -1
							|| request.getHeader("---------------") != null;
					enc = enc.indexOf("x-gzip") != -1 ? "x-gzip" : "gzip";
				}
				response.addHeader("Content-Encoding", enc);
				// -----------------------------
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				GZIPOutputStream gzipStream = new GZIPOutputStream(bos);
				gzipStream.write(inputString.getBytes(encodeType));
				gzipStream.close();
				response.setHeader("Content-Length", bos.size() + "");
				response.getOutputStream().write(bos.toByteArray());
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} else {
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(inputString);
				response.getWriter().close();
			}
			// /------------------end zip-----------------
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
